package com.ruoyi.project.data.service.impl;

import java.text.ParseException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hikvision.artemis.sdk.ArtemisHttpUtil;
import com.hikvision.artemis.sdk.config.ArtemisConfig;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.VideoUtils;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.project.data.domain.WeightCarEnter;
import com.ruoyi.project.data.domain.WeightRecord;
import com.ruoyi.project.data.domain.WeightStationCamera;
import com.ruoyi.project.data.mapper.WeightCarEnterMapper;
import com.ruoyi.project.data.mapper.WeightRecordMapper;
import com.ruoyi.project.data.service.IWeightCarEnterService;
import com.ruoyi.project.system.domain.SysDictData;
import com.ruoyi.project.system.mapper.SysDictDataMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

/**
 * 车辆进场记录Service业务层处理
 *
 * @author ruoyi
 * @date 2020-03-24
 */
@Service
public class WeightCarEnterServiceImpl implements IWeightCarEnterService
{
    @Autowired
    private WeightCarEnterMapper weightCarEnterMapper;

    @Autowired
    private SysDictDataMapper dictDataMapper;

    @Autowired
    private WeightRecordMapper weightRecordMapper;

    @Value("${video.ip}")
    private String  ip;

    @Value("${video.appKey}")
    private String  appKey;

    @Value("${video.appSecret}")
    private String  appSecret;

    @Value("${video.keyPath}")
    private String  keyPath;


    static {
        ArtemisConfig.host ="218.90.184.190";
        ArtemisConfig.appKey ="27244333";
        ArtemisConfig.appSecret ="lUxqimU0lvl4tACvY2ol";
    }

    /**
     * 查询车辆进场记录
     *
     * @param id 车辆进场记录ID
     * @return 车辆进场记录
     */
    @Override
    public WeightCarEnter selectWeightCarEnterById(Long id)
    {
        return weightCarEnterMapper.selectWeightCarEnterById(id);
    }

    /**
     * 查询车辆进场记录列表
     *
     * @param weightCarEnter 车辆进场记录
     * @return 车辆进场记录
     */
    @Override
    public List<WeightCarEnter> selectWeightCarEnterList(WeightCarEnter weightCarEnter)
    {
        return weightCarEnterMapper.selectWeightCarEnterList(weightCarEnter);
    }

    /**
     * 新增车辆进场记录
     *
     * @param weightCarEnter 车辆进场记录
     * @return 结果
     */
    @Override
    public int insertWeightCarEnter(WeightCarEnter weightCarEnter)
    {
        weightCarEnter.setCreateTime(DateUtils.getNowDate());
        return weightCarEnterMapper.insertWeightCarEnter(weightCarEnter);
    }

    /**
     * 修改车辆进场记录
     *
     * @param weightCarEnter 车辆进场记录
     * @return 结果
     */
    @Override
    public int updateWeightCarEnter(WeightCarEnter weightCarEnter)
    {
        weightCarEnter.setUpdateTime(DateUtils.getNowDate());
        return weightCarEnterMapper.updateWeightCarEnter(weightCarEnter);
    }

    /**
     * 批量删除车辆进场记录
     *
     * @param ids 需要删除的车辆进场记录ID
     * @return 结果
     */
    @Override
    public int deleteWeightCarEnterByIds(Long[] ids)
    {
        return weightCarEnterMapper.deleteWeightCarEnterByIds(ids);
    }

    /**
     * 删除车辆进场记录信息
     *
     * @param id 车辆进场记录ID
     * @return 结果
     */
    @Override
    public int deleteWeightCarEnterById(Long id)
    {
        return weightCarEnterMapper.deleteWeightCarEnterById(id);
    }

    @Override
    public AjaxResult getBackVideoPath(Long id) {
        // 获取进出场详情
        WeightCarEnter weightCarEnter = weightCarEnterMapper.selectWeightCarEnterById(id);
        String cameraCodeNvr= weightCarEnterMapper.selectCameraCodeByIp(weightCarEnter.getFrontCameraCode());

        if (cameraCodeNvr == null){
            return  AjaxResult.error("未配置相机");
        }

        final String getSecurityApi = "/artemis/api/artemis/v1/agreementService/securityParam/appKey/"+appKey;
        Map<String, String> path = new HashMap<String, String>(2){{
            put("https://", getSecurityApi);
        }};

        String result = ArtemisHttpUtil.doGetArtemis(path, null,null,null,null);

        JSONObject json= JSON.parseObject(result);

        if (!"0".equals(json.getString("code"))){
            return  AjaxResult.error("请求系统参数错误");
        }
        JSONObject  data=json.getJSONObject("data");

        String  time=data.getString("time");
        String  timeSecret=data.getString("timeSecret");
        String  appSecret=data.getString("appSecret");

        Date date = weightCarEnter.getOccurrenceTime();

        SysDictData sysDictData= new SysDictData();
        sysDictData.setDictType("vedio_time");
        sysDictData.setDictLabel("back_time");

        List<SysDictData> dictList=  dictDataMapper.selectDictDataList(sysDictData);

//        Long  tim=Long.parseLong(dictList.get(0).getDictValue());
        Long  tim=10l;
        Long start=date.getTime()/1000;

        Long end=null;
        if(tim < 0){
            end = start -tim;
            start = start + tim;
        }else{
            end = start + tim;
            start = start - tim;
        }

        StringBuilder  str=new StringBuilder();

        str.append("hikvideoclient://ReqType:PlayBack;VersionTag:artemis;SvrIp:");
        str.append(ip);
        str.append(";");
        str.append("SvrPort:443;");
        str.append("Appkey:");
        str.append(appKey);
        str.append(";");
        str.append("AppSecret:");
        str.append(appSecret);
        str.append(";");
        str.append("time:");
        str.append(time);
        str.append(";");
        str.append("timesecret:");
        str.append(timeSecret);
        str.append(";");
        str.append("httpsflag:1;");
        str.append("CamList:");
        str.append(cameraCodeNvr);
        str.append("_");
        str.append(start);
        str.append("_");
        str.append(end);
        str.append(";");

        // 实时
//        str.append("hikvideoclient://ReqType:PlayReal;VersionTag:artemis;SvrIp:");
//        str.append(ip);
//        str.append(";");
//        str.append("SvrPort:443;");
//        str.append("Appkey:");
//        str.append(appKey);
//        str.append(";");
//        str.append("AppSecret:");
//        str.append(appSecret);
//        str.append(";");
//        str.append("time:");
//        str.append(time);
//        str.append(";");
//        str.append("timesecret:");
//        str.append(timeSecret);
//        str.append(";");
//        str.append("httpsflag:1;");
//        str.append("CamList:");
//        str.append(cameraCodeNvr);
//        str.append(";");

        Map<String,String > dd=new HashMap<>();
        dd.put("videoUrl",str.toString());
        return  AjaxResult.success(dd);
    }

    @Override
    public AjaxResult getVideoPath(Long id) {
        WeightCarEnter weightCarEnter = weightCarEnterMapper.selectWeightCarEnterById(id);
        String cameraCode = weightCarEnter.getFrontCameraCode();
        Date occurrenceTime = weightCarEnter.getOccurrenceTime();
        String startTime = DateUtils.addSecond(occurrenceTime,-30);
        String endTime = DateUtils.addSecond(occurrenceTime,30);
        if(weightCarEnter.getStationCode().contains("320282")){
            try{
                String json = VideoUtils.yxPlaybackVideo(cameraCode, startTime, endTime);
                if(json == null || "".equals(json)){
                    return AjaxResult.error("暂无进出场视频");
                }else{
                    JSONObject jsonObject = JSON.parseObject(json);
                    int code = jsonObject.getIntValue("code");
                    if(code == 0){
                        String url = jsonObject.getString("url");
                        Map<String, Object> videoMap = new HashMap<>();
                        videoMap.put("videoPath", url);
                        return AjaxResult.success(videoMap);
                    }else{
                        return AjaxResult.error("暂无进出场视频");
                    }
                }
            }catch (Exception e)
            {
                return AjaxResult.error("暂无进出场视频");
            }
        }else{
            WeightRecord weightRecord = new WeightRecord();
            weightRecord.setPlantNo(weightCarEnter.getPlantNo());
            weightRecord.setWeightTime(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, weightCarEnter.getOccurrenceTime()));
            weightRecord.setStationCode(weightCarEnter.getStationCode());
            //  根据称重记录获取称重视频路径
            Map<String, Object> videoMap = weightRecordMapper.getVideoPath(weightRecord);
            if(videoMap != null){
                return AjaxResult.success(videoMap);
            }
        }
        return AjaxResult.error("暂无进出场视频");
    }

    @Override
    public WeightCarEnter selectCarEnterByWeight(WeightRecord weightRecord) {
        return weightCarEnterMapper.selectCarEnterByWeight(weightRecord);
    }
}
